package com.gitee.candy.configer.aspect;

import com.gitee.candy.configer.customInterface.HandleParam;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

/**
 * @Author suyanlong
 * @Description 处理参数切面
 * @Date 2021/6/10 16:54
 * @Version 1.0
 * <p>
 * 将string类型的参数
 * 如果为null 或 "null"转为 ”“
 */
@Aspect
@Component
public class HandleParamAspect {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("@annotation(com.gitee.candy.configer.customInterface.HandleParam)")
    public void HandleParamPointcut() {
    }

    @Around("HandleParamPointcut()&&@annotation(handleParam)")
    public Object HandleParamAround(ProceedingJoinPoint pc, HandleParam handleParam) {
        long startTime = System.currentTimeMillis();
        try {
            MethodSignature signature = (MethodSignature) pc.getSignature();
            //获取切入方法的对象
            Method method = signature.getMethod();
            //获取参数值
            Object[] args = pc.getArgs();
            //获取参数名
            DefaultParameterNameDiscoverer discoverer = new DefaultParameterNameDiscoverer();
            String[] parameterNames = discoverer.getParameterNames(method);
            // 参数
            Parameter[] parameters = method.getParameters();
            Class<?> type = parameters[0].getType();
            //对这些参数名进行遍历，找到我们要修改的参数，获取到这个参数名在数组中的下标，并将我们需要赋的值放到参数值数据的相应位置，进行参数替换。
            for (int i = 0; i < parameterNames.length; i++) {
                if (args[i] == null || (args[i] != null && args[i].equals("null"))) {
                    args[i] = "";
                }
            }
            logger.debug("处理参数时长：{}ms", (System.currentTimeMillis() - startTime));
            //执行程序，带上修改过的参数
            Object proceed = pc.proceed(args);
            return proceed;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }
}
